package com.xinxing.learning.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

@Configuration
// @EnableConfigurationProperties(DynamicDataSourceProperties.class)
@MapperScan(basePackages = {"com.xinxing.learning.datasource.mapper"})
public class DynamicDataSourceConfig {

    // @Autowired
    // private DynamicDataSourceProperties properties;

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DruidDataSource defaultDataSource(DataSourceProperties properties) {
        DruidDataSource dataSource = DynamicDataSourceFactory.buildDruidDataSource(properties);
        return dataSource;
    }

    @Bean
    @Primary
    @DependsOn("defaultDataSource")
    public DynamicDataSource dynamicDataSource(@Qualifier("defaultDataSource") DruidDataSource defaultDataSource) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
        dynamicDataSource.setTargetDataSources(DynamicDataSource.targetDataSources);
        return dynamicDataSource;
    }
}
